<template>
  <view class="history-container">
    <!-- 头部统计 -->
    <view class="stats-section">
      <view class="stat-card">
        <text class="stat-number">{{ historyList.length }}</text>
        <text class="stat-label">训练次数</text>
      </view>
      <view class="stat-card">
        <text class="stat-number">{{ averageScore }}</text>
        <text class="stat-label">平均分</text>
      </view>
      <view class="stat-card">
        <text class="stat-number">{{ averagePerArrow }}</text>
        <text class="stat-label">箭均环数</text>
      </view>
    </view>

    <!-- 操作按钮区域 -->
    <view class="action-section">
      <!-- 正常模式的操作按钮 -->
      <template v-if="!isDeleteMode">
        <button class="action-btn export-btn" @click="exportData">
          <uni-icons type="download" size="16" color="#fff"></uni-icons>
          <text class="btn-text">导出</text>
        </button>
        <button class="action-btn import-btn" @click="importData">
          <uni-icons type="upload" size="16" color="#fff"></uni-icons>
          <text class="btn-text">导入</text>
        </button>
        <button class="action-btn delete-btn" @click="toggleDeleteMode" v-if="historyList.length > 0">
          <uni-icons type="trash" size="16" color="#fff"></uni-icons>
          <text class="btn-text">删除</text>
        </button>
      </template>
      
      <!-- 删除模式下的操作按钮 -->
      <template v-if="isDeleteMode">
        <button class="action-btn cancel-btn" @click="cancelDeleteMode">
          <uni-icons type="close" size="16" color="#fff"></uni-icons>
          <text class="btn-text">取消</text>
        </button>
        <button 
          class="action-btn confirm-delete-btn" 
          @click="confirmDelete"
          :class="{ disabled: selectedItems.length === 0 }"
        >
          <uni-icons type="checkmarkempty" size="16" color="#fff"></uni-icons>
          <text class="btn-text">删除({{ selectedItems.length }})</text>
        </button>
      </template>
    </view>

    <!-- 历史记录列表 -->
    <scroll-view class="records-section" scroll-y>
      <view class="section-header">
        <text class="section-title">训练记录</text>
        <text class="section-subtitle">共{{ historyList.length }}条记录</text>
      </view>

      <view 
        v-for="(item, index) in historyList" 
        :key="item.id || index"
        class="history-card"
        :class="{ 'delete-mode': isDeleteMode, 'selected': selectedItems.includes(item.id || index) }"
        @click="handleCardClick(item, index)"
      >
        <!-- 删除模式下的复选框 -->
        <view class="checkbox-container" v-if="isDeleteMode">
          <view class="checkbox" :class="{ checked: selectedItems.includes(item.id || index) }">
            <uni-icons type="checkmarkempty" size="16" color="#fff" v-if="selectedItems.includes(item.id || index)"></uni-icons>
          </view>
        </view>
        
        <view class="card-content-wrapper">
          <view class="card-header">
            <view class="date-info">
              <text class="date">{{ formatDate(item.date) }}</text>
              <text class="time">{{ formatTime(item.date) }}</text>
            </view>
            <view class="score-badge" :class="getScoreLevel(item.total)">
              <text class="score-value">{{ item.total }}</text>
              <text class="score-unit">环</text>
            </view>
          </view>

          <view class="card-content">
            <view class="config-row">
              <view class="config-item">
                <uni-icons type="location" size="14" color="#999"></uni-icons>
                <text>{{ item.config.distance }}</text>
              </view>
              <view class="config-item">
                <uni-icons type="paperplane" size="14" color="#999"></uni-icons>
                <text>{{ item.config.bowType }}</text>
              </view>
            </view>
            <view class="config-row">
              <view class="config-item">
                <uni-icons type="calendar" size="14" color="#999"></uni-icons>
                <text>{{ item.config.target }}</text>
              </view>
              <view class="config-item">
                <uni-icons type="arrow-right" size="14" color="#999"></uni-icons>
                <text>{{ getArrowsDisplayText(item) }}</text>
              </view>
            </view>
          </view>

          <view class="card-footer" v-if="!isDeleteMode">
            <text class="average-per-arrow">箭均环数: {{ calculateAveragePerArrow(item) }}</text>
            <uni-icons type="arrowthinright" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="historyList.length === 0" class="empty-state">
        <uni-icons type="folder-add" size="80" color="#ddd"></uni-icons>
        <text class="empty-text">暂无训练记录</text>
        <text class="empty-subtitle">开始第一次训练吧！</text>
      </view>
    </scroll-view>

    <!-- 详情弹窗 -->
    <uni-popup ref="detailPopup" type="bottom" background-color="#fff">
      <view class="detail-popup" v-if="selectedRecord">
        <view class="popup-header">
          <text class="popup-title">训练详情</text>
          <view class="header-actions">
            <button class="share-btn" @click="shareRecord">
              <uni-icons type="image" size="18" color="#fff"></uni-icons>
              <text>分享图片</text>
            </button>
            <uni-icons type="close" size="20" color="#999" @click="closeDetail"></uni-icons>
          </view>
        </view>
        
        <scroll-view class="detail-content" scroll-y>
          <view class="detail-score">
            <text class="detail-total">{{ selectedRecord.total }}环</text>
            <text class="detail-date">{{ formatFullDate(selectedRecord.date) }}</text>
          </view>

          <view class="detail-config">
            <view class="detail-item">
              <text class="label">弓种</text>
              <text class="value">{{ selectedRecord.config.bowType }}</text>
            </view>
            <view class="detail-item">
              <text class="label">距离</text>
              <text class="value">{{ selectedRecord.config.distance }}</text>
            </view>
            <view class="detail-item">
              <text class="label">靶纸</text>
              <text class="value">{{ selectedRecord.config.target }}</text>
            </view>
            <view class="detail-item">
              <text class="label">箭数</text>
              <text class="value">{{ getArrowsDisplayText(selectedRecord) }}</text>
            </view>
          </view>

          <!-- 详细统计 -->
          <view class="detail-stats">
            <view class="stats-grid">
              <view class="stat-item">
                <text class="stat-number">{{ calculateDetailStats(selectedRecord).averagePerArrow }}</text>
                <text class="stat-label">箭均环数</text>
              </view>
              <view class="stat-item">
                <text class="stat-number">{{ calculateDetailStats(selectedRecord).tenAndXCount }}</text>
                <text class="stat-label">10环+X环</text>
              </view>
              <view class="stat-item">
                <text class="stat-number">{{ calculateDetailStats(selectedRecord).xCount }}</text>
                <text class="stat-label">X环</text>
              </view>
            </view>
          </view>

          <view class="detail-scores">
            <text class="scores-title">分组成绩</text>
            <view class="scores-grid">
              <view 
                v-for="(group, index) in selectedRecord.scores" 
                :key="index"
                class="score-group-detail"
              >
                <view class="group-title">第{{ index + 1 }}组 ({{ group.subtotal }}环)</view>
                <view 
                  class="group-scores" 
                  :style="{ gridTemplateColumns: `repeat(${getArrowsPerGroup(selectedRecord)}, 1fr)` }"
                >
                  <text 
                    v-for="(score, sIndex) in group.scores" 
                    :key="sIndex"
                    class="individual-score"
                    :class="getScoreClass(score)"
                  >
                    {{ getDisplayScore(score) }}
                  </text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 分享图片生成区域（隐藏） -->
    <view class="share-canvas-container" :style="{ opacity: isGeneratingImage ? 1 : 0, zIndex: isGeneratingImage ? 9999 : -1 }">
      <view class="share-content" id="shareContent">
        <view class="share-header">
          <text class="share-title">射箭训练记录</text>
          <text class="share-date">{{ selectedRecord ? formatFullDate(selectedRecord.date) : '' }}</text>
        </view>
        
        <view class="share-score-section">
          <text class="share-total-score">{{ selectedRecord ? selectedRecord.total : 0 }}环</text>
        </view>

        <view class="share-config" v-if="selectedRecord">
          <view class="share-config-row">
            <text class="share-config-label">弓种：</text>
            <text class="share-config-value">{{ selectedRecord.config.bowType }}</text>
          </view>
          <view class="share-config-row">
            <text class="share-config-label">距离：</text>
            <text class="share-config-value">{{ selectedRecord.config.distance }}</text>
          </view>
          <view class="share-config-row">
            <text class="share-config-label">靶纸：</text>
            <text class="share-config-value">{{ selectedRecord.config.target }}</text>
          </view>
          <view class="share-config-row">
            <text class="share-config-label">箭数：</text>
            <text class="share-config-value">{{ getArrowsDisplayText(selectedRecord) }}</text>
          </view>
        </view>

        <view class="share-stats" v-if="selectedRecord">
          <view class="share-stat-item">
            <text class="share-stat-number">{{ calculateDetailStats(selectedRecord).averagePerArrow }}</text>
            <text class="share-stat-label">箭均环数</text>
          </view>
          <view class="share-stat-item">
            <text class="share-stat-number">{{ calculateDetailStats(selectedRecord).tenAndXCount }}</text>
            <text class="share-stat-label">10环+X环</text>
          </view>
          <view class="share-stat-item">
            <text class="share-stat-number">{{ calculateDetailStats(selectedRecord).xCount }}</text>
            <text class="share-stat-label">X环</text>
          </view>
        </view>

        <view class="share-scores" v-if="selectedRecord">
          <text class="share-scores-title">分组成绩</text>
          <view 
            v-for="(group, index) in selectedRecord.scores" 
            :key="index"
            class="share-group"
          >
            <view class="share-group-title">第{{ index + 1 }}组 ({{ group.subtotal }}环)</view>
            <view 
              class="share-group-scores" 
              :style="{ gridTemplateColumns: `repeat(${getArrowsPerGroup(selectedRecord)}, 1fr)` }"
            >
              <text 
                v-for="(score, sIndex) in group.scores" 
                :key="sIndex"
                class="share-score-item"
                :class="getScoreClass(score)"
              >
                {{ getDisplayScore(score) }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 导入进度弹窗 -->
    <uni-popup ref="importProgressPopup" type="center" background-color="#fff">
      <view class="import-progress">
        <text class="progress-title">导入进度</text>
        <view class="progress-bar">
          <view class="progress-fill" :style="{ width: importProgress + '%' }"></view>
        </view>
        <text class="progress-text">{{ importProgress }}%</text>
        <text class="progress-desc">{{ importMessage }}</text>
      </view>
    </uni-popup>
  </view>
  <canvas 
      canvas-id="shareCanvas" 
      :style="{ 
        width: canvasWidth + 'px', 
        height: canvasHeight + 'px',
        position: 'fixed',
        left: '-9999px',
        top: '-9999px',
        zIndex: -1
      }"
    ></canvas>
</template>

<script>
export default {
  data() {
    return {
      historyList: [],
      selectedRecord: null,
      importProgress: 0,
      importMessage: '',
      isGeneratingImage: false,
      canvasWidth: 750,
      canvasHeight: 1000,
      canvasCtx: null,
      // 删除功能相关
      isDeleteMode: false,
      selectedItems: []
    }
  },
  computed: {
    averageScore() {
      if (this.historyList.length === 0) return 0;
      const total = this.historyList.reduce((sum, item) => sum + item.total, 0);
      return Math.round(total / this.historyList.length);
    },
    
    averagePerArrow() {
      if (this.historyList.length === 0) return '0.0';
      let totalScore = 0;
      let totalArrows = 0;
      
      this.historyList.forEach(item => {
        totalScore += item.total;
        totalArrows += item.config.totalArrows;
      });
      
      return totalArrows > 0 ? (totalScore / totalArrows).toFixed(1) : '0.0';
    }
  },
  onShow() {
    this.loadHistory();
  },
  methods: {
    loadHistory() {
      this.historyList = uni.getStorageSync('trainingHistory') || [];
    },

    // 获取显示的分数（0显示为M）
    getDisplayScore(score) {
      if (!score || score === '' || score === '0') return 'M';
      return score;
    },

    // 多选删除相关方法
    toggleDeleteMode() {
      this.isDeleteMode = true;
      this.selectedItems = [];
    },

    cancelDeleteMode() {
      this.isDeleteMode = false;
      this.selectedItems = [];
    },

    handleCardClick(item, index) {
      if (this.isDeleteMode) {
        const itemId = item.id || index;
        const selectedIndex = this.selectedItems.indexOf(itemId);
        if (selectedIndex > -1) {
          this.selectedItems.splice(selectedIndex, 1);
        } else {
          this.selectedItems.push(itemId);
        }
      } else {
        this.showDetail(item);
      }
    },

    confirmDelete() {
      if (this.selectedItems.length === 0) return;
      
      uni.showModal({
        title: '确认删除',
        content: `确定要删除选中的 ${this.selectedItems.length} 条记录吗？此操作不可恢复。`,
        success: (res) => {
          if (res.confirm) {
            this.deleteSelectedRecords();
          }
        }
      });
    },

    deleteSelectedRecords() {
      // 过滤掉选中的记录
      this.historyList = this.historyList.filter((item, index) => {
        const itemId = item.id || index;
        return !this.selectedItems.includes(itemId);
      });
      
      // 保存更新后的数据
      uni.setStorageSync('trainingHistory', this.historyList);
      
      // 退出删除模式
      this.cancelDeleteMode();
      
      uni.showToast({
        title: `已删除 ${this.selectedItems.length} 条记录`,
        icon: 'success'
      });
    },

    formatDate(isoStr) {
      const date = new Date(isoStr);
      const today = new Date();
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);

      if (date.toDateString() === today.toDateString()) {
        return '今天';
      } else if (date.toDateString() === yesterday.toDateString()) {
        return '昨天';
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`;
      }
    },

    formatTime(isoStr) {
      const date = new Date(isoStr);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },

    formatFullDate(isoStr) {
      const date = new Date(isoStr);
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },

    getScoreLevel(score) {
      if (score >= 300) return 'excellent';
      if (score >= 250) return 'good';
      if (score >= 200) return 'normal';
      return 'poor';
    },

    getScoreClass(score) {
      if (!score || score === '' || score === '0') return 'score-miss';
      const scoreStr = score.toString().toUpperCase();
      if (scoreStr === 'X' || scoreStr === '10') return 'score-green';
      if (scoreStr === '9') return 'score-gold';
      if (scoreStr === '8' || scoreStr === '7') return 'score-red';
      if (scoreStr === '6' || scoreStr === '5') return 'score-blue';
      if (['4', '3', '2', '1'].includes(scoreStr)) return 'score-black';
      return 'score-miss';
    },

    getArrowsDisplayText(record) {
      if (record.config.groupCount && record.config.arrowsPerGroup) {
        return `${record.config.groupCount}组${record.config.arrowsPerGroup}箭`;
      } else {
        return `${record.config.totalArrows}箭`;
      }
    },

    getArrowsPerGroup(record) {
      if (record.config.arrowsPerGroup) {
        return record.config.arrowsPerGroup;
      } else {
        return 6;
      }
    },

    // 计算单条记录的箭均环数
    calculateAveragePerArrow(record) {
      if (!record.config || !record.config.totalArrows || record.config.totalArrows === 0) {
        return '0.0';
      }
      return (record.total / record.config.totalArrows).toFixed(1);
    },

    calculateAccuracy(record) {
      if (!record.scores || record.scores.length === 0) return 0;
      
      let hitCount = 0;
      let totalCount = 0;
      
      record.scores.forEach(group => {
        group.scores.forEach(score => {
          totalCount++;
          if (score && score !== '0' && score !== '') {
            hitCount++;
          }
        });
      });
      
      return totalCount > 0 ? Math.round((hitCount / totalCount) * 100) : 0;
    },

    calculateDetailStats(record) {
      if (!record.scores || record.scores.length === 0) {
        return {
          averagePerArrow: '0.0',
          tenAndXCount: 0,
          xCount: 0
        };
      }
      
      let totalScore = record.total;
      let totalArrows = record.config.totalArrows;
      let tenAndXCount = 0;
      let xCount = 0;
      
      record.scores.forEach(group => {
        group.scores.forEach(score => {
          if (score === 'X') {
            xCount++;
            tenAndXCount++;
          } else if (score === '10') {
            tenAndXCount++;
          }
        });
      });
      
      return {
        averagePerArrow: totalArrows > 0 ? (totalScore / totalArrows).toFixed(1) : '0.0',
        tenAndXCount,
        xCount
      };
    },

    showDetail(record) {
      this.selectedRecord = record;
      this.$refs.detailPopup.open();
    },

    closeDetail() {
      this.$refs.detailPopup.close();
      this.selectedRecord = null;
    },

    shareRecord() {
      if (!this.selectedRecord) return;
      
      uni.showLoading({
        title: '生成图片中...',
        mask: true
      });
      
      this.isGeneratingImage = true;
      
      this.$nextTick(() => {
        setTimeout(() => {
          this.drawCanvasImage();
        }, 500);
      });
    },
    
    // 绘制优化后的canvas图片
    drawCanvasImage() {
      const estimatedHeight = this.calculateCanvasHeight();
      this.canvasHeight = estimatedHeight;
      
      const ctx = uni.createCanvasContext('shareCanvas', this);
      this.canvasCtx = ctx;
      
      // 设置渐变背景
      const gradient = ctx.createLinearGradient(0, 0, 0, this.canvasHeight);
      gradient.addColorStop(0, '#f8faff');
      gradient.addColorStop(1, '#ffffff');
      ctx.setFillStyle(gradient);
      ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      
      let currentY = 60;
      
      // 绘制装饰性顶部
      ctx.setFillStyle('#4a8cff');
      ctx.fillRect(0, 0, this.canvasWidth, 8);
      
      // 绘制标题
      ctx.setFillStyle('#2c3e50');
      ctx.setFontSize(44);
      ctx.setTextAlign('center');
      ctx.fillText('🏹 射箭训练记录', this.canvasWidth / 2, currentY);
      currentY += 50;
      
      // 绘制日期
      ctx.setFillStyle('#7f8c8d');
      ctx.setFontSize(26);
      ctx.setTextAlign('center');
      ctx.fillText(this.formatFullDate(this.selectedRecord.date), this.canvasWidth / 2, currentY);
      currentY += 100; // 增加日期与圆形的距离
      
      // 绘制总分圆形背景
      const centerX = this.canvasWidth / 2;
      const radius = 80;
      
      // 外圆阴影
      ctx.setFillStyle('rgba(0,0,0,0.1)');
      ctx.beginPath();
      ctx.arc(centerX + 2, currentY + 2, radius, 0, 2 * Math.PI);
      ctx.fill();
      
      // 外圆
      ctx.setFillStyle('#4a8cff');
      ctx.beginPath();
      ctx.arc(centerX, currentY, radius, 0, 2 * Math.PI);
      ctx.fill();
      
      // 内圆
      ctx.setFillStyle('#ffffff');
      ctx.beginPath();
      ctx.arc(centerX, currentY, radius - 8, 0, 2 * Math.PI);
      ctx.fill();
      
      // 总分文字
      ctx.setFillStyle('#4a8cff');
      ctx.setFontSize(52);
      ctx.setTextAlign('center');
      ctx.fillText(this.selectedRecord.total.toString(), centerX, currentY + 8);
      
      ctx.setFillStyle('#7f8c8d');
      ctx.setFontSize(24);
      ctx.fillText('环', centerX, currentY + 35);
      
      currentY += radius + 80;
      
      // 绘制配置信息卡片
      currentY = this.drawStyledConfigSection(ctx, currentY);
      currentY += 40;
      
      // 绘制统计信息卡片（移除图标）
      currentY = this.drawStyledStatsSection(ctx, currentY);
      currentY += 40;
      
      // 绘制成绩详情
      this.drawStyledScoresSection(ctx, currentY);
      
      ctx.draw(false, () => {
        setTimeout(() => {
          this.saveCanvasImage();
        }, 500);
      });
    },
    
    calculateCanvasHeight() {
      const baseHeight = 450;
      const configHeight = 220;
      const statsHeight = 140; // 减少了图标区域的高度
      const scoresHeight = this.selectedRecord.scores.length * 140 + 120;
      
      return baseHeight + configHeight + statsHeight + scoresHeight;
    },
    
    // 绘制带圆角和阴影的配置区域
    drawStyledConfigSection(ctx, startY) {
      const configs = [
        { label: '弓种', value: this.selectedRecord.config.bowType },
        { label: '距离', value: this.selectedRecord.config.distance },
        { label: '靶纸', value: this.selectedRecord.config.target },
        { label: '箭数', value: this.getArrowsDisplayText(this.selectedRecord) }
      ];
      
      const padding = 30;
      const cardHeight = 180;
      const radius = 16;
      
      // 绘制卡片阴影
      ctx.setFillStyle('rgba(0,0,0,0.08)');
      this.drawRoundedRect(ctx, padding + 2, startY + 2, this.canvasWidth - padding * 2, cardHeight, radius);
      ctx.fill();
      
      // 绘制卡片背景
      ctx.setFillStyle('#ffffff');
      this.drawRoundedRect(ctx, padding, startY, this.canvasWidth - padding * 2, cardHeight, radius);
      ctx.fill();
      
      // 绘制卡片边框
      ctx.setStrokeStyle('#e8eaed');
      ctx.setLineWidth(1);
      this.drawRoundedRect(ctx, padding, startY, this.canvasWidth - padding * 2, cardHeight, radius);
      ctx.stroke();
      
      // 绘制标题
      ctx.setFillStyle('#2c3e50');
      ctx.setFontSize(28);
      ctx.setTextAlign('left');
      ctx.fillText('📋 训练配置', padding + 20, startY + 35);
      
      // 绘制配置项
      configs.forEach((config, index) => {
        const row = Math.floor(index / 2);
        const col = index % 2;
        const itemWidth = (this.canvasWidth - padding * 2 - 40) / 2;
        const x = padding + 20 + col * (itemWidth + 20);
        const y = startY + 70 + row * 45;
        
        // 标签
        ctx.setFillStyle('#5a6c7d');
        ctx.setFontSize(24);
        ctx.setTextAlign('left');
        ctx.fillText(config.label + ':', x, y);
        
        // 值
        ctx.setFillStyle('#2c3e50');
        ctx.setFontSize(24);
        ctx.fillText(config.value, x + 80, y);
      });
      
      return startY + cardHeight;
    },
    
    // 绘制统计信息卡片（移除图标）
    drawStyledStatsSection(ctx, startY) {
      const stats = this.calculateDetailStats(this.selectedRecord);
      const statItems = [
        { label: '箭均环数', value: stats.averagePerArrow },
        { label: '10环+X环', value: stats.tenAndXCount },
        { label: 'X环', value: stats.xCount }
      ];
      
      const padding = 30;
      const cardHeight = 100; // 减少高度
      const radius = 16;
      const itemWidth = (this.canvasWidth - padding * 2 - 40) / 3;
      
      statItems.forEach((stat, index) => {
        const x = padding + index * (itemWidth + 20);
        
        // 绘制统计卡片阴影
        ctx.setFillStyle('rgba(0,0,0,0.08)');
        this.drawRoundedRect(ctx, x + 2, startY + 2, itemWidth, cardHeight, radius);
        ctx.fill();
        
        // 绘制统计卡片背景
        ctx.setFillStyle('#ffffff');
        this.drawRoundedRect(ctx, x, startY, itemWidth, cardHeight, radius);
        ctx.fill();
        
        // 绘制统计卡片边框
        ctx.setStrokeStyle('#e8eaed');
        ctx.setLineWidth(1);
        this.drawRoundedRect(ctx, x, startY, itemWidth, cardHeight, radius);
        ctx.stroke();
        
        const centerX = x + itemWidth / 2;
        
        // 数值
        ctx.setFillStyle('#4a8cff');
        ctx.setFontSize(32);
        ctx.setTextAlign('center');
        ctx.fillText(stat.value.toString(), centerX, startY + 40);
        
        // 标签
        ctx.setFillStyle('#7f8c8d');
        ctx.setFontSize(20);
        ctx.fillText(stat.label, centerX, startY + 70);
      });
      
      return startY + cardHeight;
    },
    
    // 绘制成绩详情
    drawStyledScoresSection(ctx, startY) {
      let currentY = startY;
      
      // 标题
      ctx.setFillStyle('#2c3e50');
      ctx.setFontSize(32);
      ctx.setTextAlign('left');
      ctx.fillText('🎯 分组成绩', 40, currentY);
      currentY += 50;
      
      const arrowsPerGroup = this.getArrowsPerGroup(this.selectedRecord);
      const padding = 30;
      const cellWidth = (this.canvasWidth - padding * 2) / arrowsPerGroup;
      const cellHeight = 70;
      const radius = 8;
      
      this.selectedRecord.scores.forEach((group, groupIndex) => {
        // 组标题背景
        ctx.setFillStyle('#f8f9fa');
        this.drawRoundedRect(ctx, padding, currentY, this.canvasWidth - padding * 2, 35, 8);
        ctx.fill();
        
        // 组标题
        ctx.setFillStyle('#495057');
        ctx.setFontSize(26);
        ctx.setTextAlign('left');
        ctx.fillText(`第${groupIndex + 1}组`, padding + 15, currentY + 24);
        
        // 组小计
        ctx.setTextAlign('right');
        ctx.fillText(`${group.subtotal}环`, this.canvasWidth - padding - 15, currentY + 24);
        currentY += 45;
        
        // 绘制成绩格子
        group.scores.forEach((score, scoreIndex) => {
          const x = padding + (scoreIndex * cellWidth);
          const scoreClass = this.getScoreClass(score);
          const displayScore = this.getDisplayScore(score);
          
          let bgColor = '#ffffff';
          let textColor = '#333333';
          let borderColor = '#e8eaed';
          
          switch(scoreClass) {
            case 'score-green':
              bgColor = '#28a745';
              textColor = '#ffffff';
              borderColor = '#1e7e34';
              break;
            case 'score-gold':
              bgColor = '#ffc107';
              textColor = '#212529';
              borderColor = '#d39e00';
              break;
            case 'score-red':
              bgColor = '#dc3545';
              textColor = '#ffffff';
              borderColor = '#bd2130';
              break;
            case 'score-blue':
              bgColor = '#007bff';
              textColor = '#ffffff';
              borderColor = '#0056b3';
              break;
            case 'score-black':
              bgColor = '#6c757d';
              textColor = '#ffffff';
              borderColor = '#495057';
              break;
            case 'score-miss':
              bgColor = '#ffffff';
              textColor = '#6c757d';
              borderColor = '#e8eaed';
              break;
          }
          
          // 绘制成绩格子阴影
          ctx.setFillStyle('rgba(0,0,0,0.1)');
          this.drawRoundedRect(ctx, x + 2, currentY + 2, cellWidth - 8, cellHeight, radius);
          ctx.fill();
          
          // 绘制成绩格子背景
          ctx.setFillStyle(bgColor);
          this.drawRoundedRect(ctx, x, currentY, cellWidth - 8, cellHeight, radius);
          ctx.fill();
          
          // 绘制成绩格子边框
          ctx.setStrokeStyle(borderColor);
          ctx.setLineWidth(2);
          this.drawRoundedRect(ctx, x, currentY, cellWidth - 8, cellHeight, radius);
          ctx.stroke();
          
          // 绘制成绩文字
          ctx.setFillStyle(textColor);
          ctx.setFontSize(28);
          ctx.setTextAlign('center');
          ctx.fillText(displayScore, x + (cellWidth - 8) / 2, currentY + cellHeight / 2 + 10);
        });
        
        currentY += cellHeight + 25;
      });
      
      this.canvasHeight = currentY + 50;
    },
    
    // 绘制圆角矩形的辅助方法
    drawRoundedRect(ctx, x, y, width, height, radius) {
      ctx.beginPath();
      ctx.moveTo(x + radius, y);
      ctx.lineTo(x + width - radius, y);
      ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
      ctx.lineTo(x + width, y + height - radius);
      ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
      ctx.lineTo(x + radius, y + height);
      ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
      ctx.lineTo(x, y + radius);
      ctx.quadraticCurveTo(x, y, x + radius, y);
      ctx.closePath();
    },
    
    saveCanvasImage() {
      uni.canvasToTempFilePath({
        canvasId: 'shareCanvas',
        width: this.canvasWidth,
        height: this.canvasHeight,
        destWidth: this.canvasWidth * 2,
        destHeight: this.canvasHeight * 2,
        fileType: 'png',
        quality: 1,
        success: (res) => {
          this.isGeneratingImage = false;
          uni.hideLoading();
          
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              uni.showToast({
                title: '图片已保存到相册',
                icon: 'success'
              });
            },
            fail: (err) => {
              console.log('保存失败:', err);
              uni.previewImage({
                urls: [res.tempFilePath],
                current: res.tempFilePath
              });
            }
          });
        },
        fail: (err) => {
          console.error('生成图片失败:', err);
          this.isGeneratingImage = false;
          uni.hideLoading();
          uni.showToast({
            title: '生成图片失败',
            icon: 'error'
          });
        }
      }, this);
    },

    exportData() {
      if (this.historyList.length === 0) {
        uni.showToast({
          title: '暂无数据可导出',
          icon: 'none'
        });
        return;
      }

      try {
        const jsonData = this.prepareJsonData();
        const jsonString = JSON.stringify(jsonData, null, 2);
        
        const fs = uni.getFileSystemManager();
        const fileName = `archery_records_${new Date().getTime()}.json`;
        const filePath = `${uni.env.USER_DATA_PATH}/${fileName}`;
        
        fs.writeFileSync(filePath, jsonString, 'utf8');
        
        uni.shareFileMessage({
          filePath: filePath,
          success: () => {
            uni.showToast({
              title: '导出成功',
              icon: 'success'
            });
          },
          fail: (err) => {
            console.error('分享失败:', err);
            uni.setClipboardData({
              data: jsonString,
              success: () => {
                uni.showToast({
                  title: '数据已复制到剪贴板',
                  icon: 'success'
                });
              }
            });
          }
        });
        
      } catch (error) {
        console.error('导出失败:', error);
        uni.showToast({
          title: '导出失败',
          icon: 'error'
        });
      }
    },

    prepareJsonData() {
      return this.historyList.map(record => ({
        timestamp: record.timestamp || record.id,
        userId: record.userId || '',
        date: record.date,
        bowType: record.config.bowType,
        distance: record.config.distance,
        target: record.config.target,
        totalArrows: record.config.totalArrows,
        groupCount: record.config.groupCount || Math.ceil(record.config.totalArrows / 6),
        arrowsPerGroup: record.config.arrowsPerGroup || 6,
        scores: record.scores,
        total: record.total
      }));
    },

    importData() {
      uni.chooseMessageFile({
        count: 1,
        type: 'file',
        success: (res) => {
          const filePath = res.tempFiles[0].path;
          this.processImportFile(filePath);
        },
        fail: (err) => {
          console.error('选择文件失败:', err);
          uni.showToast({
            title: '选择文件失败',
            icon: 'error'
          });
        }
      });
    },

    processImportFile(filePath) {
      this.importProgress = 0;
      this.importMessage = '正在读取文件...';
      this.$refs.importProgressPopup.open();

      try {
        const fs = uni.getFileSystemManager();
        const fileContent = fs.readFileSync(filePath, 'utf8');
        
        this.importProgress = 30;
        this.importMessage = '正在解析数据...';

        const importedData = JSON.parse(fileContent);
        
        if (!Array.isArray(importedData)) {
          throw new Error('文件格式不正确');
        }

        this.importProgress = 60;
        this.importMessage = '正在合并数据...';

        this.mergeImportedData(importedData);

        this.importProgress = 100;
        this.importMessage = '导入完成！';

        setTimeout(() => {
          this.$refs.importProgressPopup.close();
          this.loadHistory();
          
          uni.showToast({
            title: '导入成功',
            icon: 'success'
          });
        }, 1000);

      } catch (error) {
        console.error('导入失败:', error);
        this.$refs.importProgressPopup.close();
        
        uni.showToast({
          title: '导入失败：' + error.message,
          icon: 'none',
          duration: 3000
        });
      }
    },

    mergeImportedData(importedData) {
      const currentHistory = uni.getStorageSync('trainingHistory') || [];
      const currentUserId = getApp().globalData.userId || uni.getStorageSync('userId');
      
      const timestampMap = new Map();
      
      currentHistory.forEach(record => {
        const key = record.timestamp || record.id;
        timestampMap.set(key, record);
      });
      
      let importCount = 0;
      let updateCount = 0;
      
      importedData.forEach(importedRecord => {
        if (!this.validateRecordFormat(importedRecord)) {
          return;
        }
        
        const convertedRecord = this.convertImportedRecord(importedRecord, currentUserId);
        const key = convertedRecord.timestamp || convertedRecord.id;
        
        if (timestampMap.has(key)) {
          timestampMap.set(key, convertedRecord);
          updateCount++;
        } else {
          timestampMap.set(key, convertedRecord);
          importCount++;
        }
      });
      
      const mergedHistory = Array.from(timestampMap.values())
        .sort((a, b) => (b.timestamp || b.id) - (a.timestamp || a.id));
      
      if (mergedHistory.length > 200) {
        mergedHistory.splice(200);
      }
      
      uni.setStorageSync('trainingHistory', mergedHistory);
      
      console.log(`导入完成: 新增${importCount}条, 更新${updateCount}条`);
    },

    validateRecordFormat(record) {
      return record && 
             typeof record.timestamp !== 'undefined' &&
             record.date && 
             record.bowType &&
             record.distance &&
             record.target &&
             typeof record.totalArrows === 'number' &&
             Array.isArray(record.scores) &&
             typeof record.total === 'number';
    },

    convertImportedRecord(importedRecord, currentUserId) {
      return {
        id: importedRecord.timestamp,
        timestamp: importedRecord.timestamp,
        userId: importedRecord.userId || currentUserId || 'unknown',
        date: importedRecord.date,
        config: {
          bowType: importedRecord.bowType,
          distance: importedRecord.distance,
          target: importedRecord.target,
          totalArrows: importedRecord.totalArrows,
          groupCount: importedRecord.groupCount || Math.ceil(importedRecord.totalArrows / 6),
          arrowsPerGroup: importedRecord.arrowsPerGroup || 6
        },
        scores: importedRecord.scores,
        total: importedRecord.total
      };
    }
  }
}
</script>

<style lang="scss">
$primary-color: #4a8cff;
$success-color: #52c41a;
$warning-color: #faad14;
$error-color: #ff4d4f;
$text-color: #333;
$text-light: #666;
$text-lighter: #999;
$bg-color: #f5f6fa;

// 统一分数颜色定义（以图片配色为准）
$score-green: #28a745;
$score-gold: #ffc107;
$score-red: #dc3545;
$score-blue: #007bff;
$score-black: #6c757d;
$score-miss: #ffffff;

.history-container {
  background: $bg-color;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
}

.stats-section {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  gap: 15rpx;
  width: 100%;
  box-sizing: border-box;
}

.stat-card {
  flex: 1;
  background: white;
  border-radius: 16rpx;
  padding: 24rpx 16rpx;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.04);
  min-width: 0;

  .stat-number {
    display: block;
    font-size: 40rpx;
    font-weight: bold;
    color: $primary-color;
    margin-bottom: 8rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .stat-label {
    font-size: 22rpx;
    color: $text-lighter;
    white-space: nowrap;
  }
}

.action-section {
  display: flex;
  gap: 15rpx;
  padding: 0 20rpx 20rpx;
  flex-wrap: wrap;
}

.action-btn {
  height: 70rpx;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  font-size: 26rpx;
  font-weight: 500;
  padding: 0 20rpx;
  min-width: 120rpx;
  
  &::after {
    border: none;
  }
  
  .btn-text {
    white-space: nowrap;
  }
  
  // 正常模式下，三个按钮平分
  &:not(.cancel-btn):not(.confirm-delete-btn) {
    flex: 1;
  }
  
  // 删除模式下，两个按钮平分
  &.cancel-btn,
  &.confirm-delete-btn {
    flex: 1;
  }
  
  &.export-btn {
    background: $primary-color;
    color: white;
  }
  
  &.import-btn {
    background: $success-color;
    color: white;
  }
  
  &.delete-btn {
    background: $error-color;
    color: white;
  }
  
  &.cancel-btn {
    background: #6c757d;
    color: white;
  }
  
  &.confirm-delete-btn {
    background: $error-color;
    color: white;
    
    &.disabled {
      background: #ccc;
      color: #999;
    }
  }
}

.records-section {
  height: calc(100vh - 260rpx);
  padding: 0 20rpx;
  box-sizing: border-box;
  width: 100%;
}

.section-header {
  padding: 20rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .section-title {
    font-size: 36rpx;
    font-weight: 600;
    color: $text-color;
  }

  .section-subtitle {
    font-size: 28rpx;
    color: $text-lighter;
  }
}

.history-card {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.06);
  transition: all 0.2s;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  display: flex;
  align-items: center;
  overflow: hidden;

  &:active {
    transform: scale(0.98);
  }
  
  &.delete-mode {
    &.selected {
      background: rgba($primary-color, 0.05);
      border: 2rpx solid $primary-color;
    }
  }
}

.checkbox-container {
  position: absolute;
  left: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  
  &.checked {
    background: $primary-color;
    border-color: $primary-color;
  }
}

.card-content-wrapper {
  flex: 1;
  padding: 24rpx;
  padding-left: 24rpx;
  
  .delete-mode & {
    padding-left: 80rpx;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.date-info {
  flex: 1;
  min-width: 0;
  
  .date {
    font-size: 32rpx;
    font-weight: 500;
    color: $text-color;
    margin-right: 12rpx;
  }

  .time {
    font-size: 24rpx;
    color: $text-lighter;
  }
}

.score-badge {
  display: flex;
  align-items: baseline;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  white-space: nowrap;

  &.excellent {
    background: rgba($success-color, 0.1);
    color: $success-color;
  }

  &.good {
    background: rgba($primary-color, 0.1);
    color: $primary-color;
  }

  &.normal {
    background: rgba($warning-color, 0.1);
    color: $warning-color;
  }

  &.poor {
    background: rgba($error-color, 0.1);
    color: $error-color;
  }

  .score-value {
    font-size: 32rpx;
    font-weight: bold;
  }

  .score-unit {
    font-size: 24rpx;
    margin-left: 4rpx;
    opacity: 0.8;
  }
}

.card-content {
  margin-bottom: 16rpx;
}

.config-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.config-item {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: $text-light;
  flex: 1;
  min-width: 0;

  text {
    margin-left: 8rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;

  .average-per-arrow {
    font-size: 26rpx;
    color: $text-lighter;
  }
}

.empty-state {
  text-align: center;
  padding: 120rpx 40rpx;

  .empty-text {
    display: block;
    font-size: 32rpx;
    color: $text-lighter;
    margin: 32rpx 0 16rpx;
  }

  .empty-subtitle {
    font-size: 28rpx;
    color: #ddd;
  }
}

.detail-popup {
  padding: 40rpx;
  border-radius: 24rpx 24rpx 0 0;
  height: 85vh;
  width: 100%;
  box-sizing: border-box;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;

  .popup-title {
    font-size: 36rpx;
    font-weight: 600;
    color: $text-color;
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 20rpx;
  }

  .share-btn {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 12rpx 20rpx;
    background: $primary-color;
    color: white;
    border-radius: 20rpx;
    font-size: 24rpx;
    
    &::after {
      border: none;
    }
  }
}

.detail-content {
  height: calc(85vh - 120rpx);
  width: 100%;
  box-sizing: border-box;
  
  .detail-score {
    text-align: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    margin-bottom: 32rpx;

    .detail-total {
      display: block;
      font-size: 64rpx;
      font-weight: bold;
      color: $primary-color;
      margin-bottom: 16rpx;
    }

    .detail-date {
      font-size: 28rpx;
      color: $text-lighter;
    }
  }

  .detail-config {
    margin-bottom: 32rpx;

    .detail-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f8f8f8;

      .label {
        font-size: 28rpx;
        color: $text-light;
      }

      .value {
        font-size: 28rpx;
        color: $text-color;
        font-weight: 500;
      }
    }
  }

  .detail-stats {
    margin-bottom: 32rpx;
    padding: 24rpx;
    background: #f8f9fa;
    border-radius: 12rpx;

    .stats-grid {
      display: flex;
      justify-content: space-between;
      gap: 20rpx;
    }

    .stat-item {
      flex: 1;
      text-align: center;

      .stat-number {
        display: block;
        font-size: 36rpx;
        font-weight: bold;
        color: $primary-color;
        margin-bottom: 8rpx;
      }

      .stat-label {
        font-size: 24rpx;
        color: $text-lighter;
      }
    }
  }

  .detail-scores {
    .scores-title {
      display: block;
      font-size: 32rpx;
      font-weight: 600;
      color: $text-color;
      margin-bottom: 24rpx;
    }
  }
}

.score-group-detail {
  margin-bottom: 32rpx;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;

  .group-title {
    font-size: 28rpx;
    color: $text-light;
    margin-bottom: 16rpx;
  }

  .group-scores {
    display: grid;
    gap: 12rpx;
  }
}

// 统一的成绩颜色样式
.individual-score {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: 500;
  color: white;

  &.score-green {
    background: $score-green;
    color: white;
  }

  &.score-gold {
    background: $score-gold;
    color: #212529;
  }

  &.score-red {
    background: $score-red;
    color: white;
  }

  &.score-blue {
    background: $score-blue;
    color: white;
  }

  &.score-black {
    background: $score-black;
    color: white;
  }

  &.score-miss {
    background: $score-miss;
    color: $text-color;
    border: 1rpx solid #ddd;
  }
}

// 分享图片样式
.share-canvas-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
  padding: 40rpx;
}

.share-content {
  width: 100%;
  background: white;
  padding: 40rpx;
}

.share-header {
  text-align: center;
  margin-bottom: 40rpx;
  border-bottom: 2rpx solid #eee;
  padding-bottom: 30rpx;

  .share-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: $text-color;
    margin-bottom: 16rpx;
  }

  .share-date {
    font-size: 28rpx;
    color: $text-lighter;
  }
}

.share-score-section {
  text-align: center;
  margin-bottom: 40rpx;

  .share-total-score {
    font-size: 80rpx;
    font-weight: bold;
    color: $primary-color;
  }
}

.share-config {
  margin-bottom: 40rpx;
  padding: 30rpx;
  background: #f8f9fa;
  border-radius: 16rpx;

  .share-config-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
    font-size: 32rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .share-config-label {
      color: $text-light;
    }

    .share-config-value {
      color: $text-color;
      font-weight: 500;
    }
  }
}

.share-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40rpx;
  gap: 20rpx;

  .share-stat-item {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    background: #f8f9fa;
    border-radius: 12rpx;

    .share-stat-number {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: $primary-color;
      margin-bottom: 8rpx;
    }

    .share-stat-label {
      font-size: 24rpx;
      color: $text-lighter;
    }
  }
}

.share-scores {
  .share-scores-title {
    display: block;
    font-size: 32rpx;
    font-weight: 600;
    color: $text-color;
    margin-bottom: 24rpx;
  }

  .share-group {
    margin-bottom: 30rpx;
    padding: 24rpx;
    background: #f8f9fa;
    border-radius: 12rpx;

    .share-group-title {
      font-size: 28rpx;
      color: $text-light;
      margin-bottom: 16rpx;
    }

    .share-group-scores {
      display: grid;
      gap: 12rpx;
    }

    .share-score-item {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 60rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      font-weight: 500;
      color: white;

      &.score-green {
        background: $score-green;
        color: white;
      }

      &.score-gold {
        background: $score-gold;
        color: #212529;
      }

      &.score-red {
        background: $score-red;
        color: white;
      }

      &.score-blue {
        background: $score-blue;
        color: white;
      }

      &.score-black {
        background: $score-black;
        color: white;
      }

      &.score-miss {
        background: $score-miss;
        color: $text-color;
        border: 1rpx solid #ddd;
      }
    }
  }
}

.import-progress {
  padding: 60rpx 40rpx;
  text-align: center;
  min-width: 500rpx;

  .progress-title {
    display: block;
    font-size: 36rpx;
    font-weight: 600;
    color: $text-color;
    margin-bottom: 40rpx;
  }

  .progress-bar {
    width: 100%;
    height: 12rpx;
    background: #f0f0f0;
    border-radius: 6rpx;
    overflow: hidden;
    margin-bottom: 20rpx;

    .progress-fill {
      height: 100%;
      background: $primary-color;
      border-radius: 6rpx;
      transition: width 0.3s ease;
    }
  }

  .progress-text {
    display: block;
    font-size: 32rpx;
    font-weight: 600;
    color: $primary-color;
    margin-bottom: 20rpx;
  }

  .progress-desc {
    font-size: 28rpx;
    color: $text-light;
  }
}
</style>